package com.veetao.api.filter;

import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.math.NumberUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.veetao.api.consts.HttpConstants;
import com.veetao.api.model.ApiResult;
import com.veetao.api.model.ApiResultCode;
import com.veetao.api.model.AppClientInfo;
import com.veetao.api.service.CommandLookupService;
import com.veetao.api.service.MobileClientAppService;
import com.veetao.api.utils.ConfigUtils;
import com.veetao.api.utils.McpUtils;
import com.veetao.api.utils.RequestUtils;

@Component
public class CommonParamsChecker extends ApiRequestChecker {
	public CommonParamsChecker() {
		super();
		this.setOrder(1);
	}


	@Autowired
	private MobileClientAppService mobileClientAppService;
	@Autowired
	private CommandLookupService commandLookupService;

	@Override
	public ApiResult check(HttpServletRequest request) {
		
		final Map<String, String> httpHeads = McpUtils.getHttpHeads(request);
		final int appId = NumberUtils.toInt(RequestUtils.get(request, HttpConstants.PARAM_APP_ID));
		AppClientInfo appInfo = mobileClientAppService.getAppInfo(appId);
		// 接入信息无效
		if (appInfo == null) {
			// 当开启DEBUG_MODE时，当传入的appId无效时，使用测试用的appId
			if (StringUtils.equalsIgnoreCase(ConfigUtils.DEBUG_MODE, "test")) {
				appInfo = mobileClientAppService.getAppInfo(1); // 1是测试用到appId
			} else {
				return new ApiResult(ApiResultCode.E_SYS_INVALID_APP_ID);
			}
		}
		
		if(!isNeedCheckSignature(request)) {
			// 不需要签名。 对一些不敏感，简单的接口可用设置不需要签名。 慎用！！
			return SUCC_RESULT;
		}
		
		
		String sig = RequestUtils.get(request, HttpConstants.PARAM_SIG);
		// sig is required
		if (StringUtils.isEmpty(sig)) {
			return new ApiResult(ApiResultCode.E_SYS_INVALID_SIG);
		}
		String secretKey = appInfo.getAppSecretKey();
		
		Map<String, String> parameterMap = McpUtils.fillParamMap(request);
		String normalizedString = McpUtils.generateNormalizedString(httpHeads, parameterMap );
		String requiredSig = McpUtils.generateSignature(normalizedString, secretKey);
		if (!StringUtils.equalsIgnoreCase(sig, requiredSig)) {
				return new ApiResult(ApiResultCode.E_SYS_INVALID_SIG);
		}
		return SUCC_RESULT;
	}

	/**
	 * @param request
	 * @return
	 * @author guohongtao
	 */
	private boolean isNeedCheckSignature(HttpServletRequest request) {
		String methodName = McpUtils.getCmdMethodFromURI(request.getRequestURI());
		
		String version = RequestUtils.get(request, HttpConstants.PARAM_VER);
		return this.commandLookupService.needCheckSignature(methodName, version);
	}
	
	
	
	

}
